<template>
  <div :class="{'mobile-notice': showMobilePage}" class="flyPrice">
    <div class="flex-center tab-wrap">
      <ListTab
        v-if="showMobilePage"
        v-model="tabStatus"
        :show-header="false"
        :tabs="tabs"
        :max-badge="{ num: 10000, str: '1w', unit:'+'}"
        class="tabs"
        @tabClick="handleTabClick" />
      <DetailTabs v-else v-model="tabStatus" :tabs="tabs" :max-badge="{ num: 10000, str: '1w', unit:'+'}" @tabClick="handleTabClick"/>
      <div class="filter-wrap">
        <FilterInput
          v-if="showMobilePage"
          ref="FilterToolRef"
          v-model="paramsObj"
          :filter-list="filterList"
          show-search-btn
          show-mobile-icon
          class="filter-btn"
          @handelClick="queryClick"
          @queryEmpty="queryEmpty"
          @filterTagStatus="filterTagStatus" />
      </div>
    </div>
    <div class="flyPrice-list">
      <div class="filter">
        <FilterInput
          v-if="!showMobilePage"
          ref="FilterToolRef"
          v-model="paramsObj"
          :filter-list="filterList"
          show-search-btn
          class="filter-btn"
          @handelClick="queryClick"
          @queryEmpty="queryEmpty"
          @filterTagStatus="filterTagStatus" />
        <div v-if="showMobilePage" :class="{'notice-btn-group':showPriceBtn || isCreator}">
          <el-button v-if="showPressBtn" size="small" class="common-btn" @click="handlePress">催办</el-button>
          <el-button v-if="showNoticeBtn" size="small" class="common-btn" @click="handleNotice">通知签约经纪</el-button>
          <el-button v-if="showAddRemarkBtn" size="small" class="common-btn" @click="openAdditionalDialog">追加说明</el-button>
          <el-button v-if="showAddAccount" size="small" class="common-btn" @click="additionalAccount">追加账号</el-button>
          <el-button v-if="showAuditBtn" size="small" type="primary" class="common-btn" @click="toAudit({ type: 'pass' })">审核通过</el-button>
          <el-button v-if="showAuditBtn" size="small" class="revoke-btn common-btn" @click="toAudit({ type: 'refuse' })">驳回修改</el-button>
          <el-button v-if="showRevoke" size="small" class="revoke-btn common-btn" @click="toAudit({ isRevoke: true })">撤回待审核</el-button>
          <el-button v-if="showSyncBtn" :disabled="syncLoading" size="small" type="primary" class="common-btn" @click="syncData()">{{ syncLoading?'数据同步中':'立即同步' }}<i v-if="syncLoading" class="el-icon-loading"/></el-button>
          <btnGroup
            v-if="tabs.length"
            ref="btnGroupRef"
            :list="[
              {label:'导出', exportApi:'/admin/queryPriceItem/list/export', exportName:'询价列表', beforeExport: exportBeforeExport, type: 'export'}
            ]"
            class="btns"
            style="margin-left:16px"
            @onComplate="exportComplete"
          />
        </div>
        <template v-else>
          <el-button v-if="showPressBtn" size="small" class="common-btn" @click="handlePress">催办</el-button>
          <el-button v-if="showNoticeBtn" size="small" class="common-btn" @click="handleNotice">通知签约经纪</el-button>
          <el-button v-if="showAddRemarkBtn" size="small" class="common-btn" @click="openAdditionalDialog">追加说明</el-button>
          <el-button v-if="showAddAccount" size="small" class="common-btn" @click="additionalAccount">追加账号</el-button>
          <el-button v-if="showAuditBtn" size="small" type="primary" class="common-btn" @click="toAudit({ type: 'pass' })">审核通过</el-button>
          <el-button v-if="showAuditBtn" size="small" class="revoke-btn common-btn" @click="toAudit({ type: 'refuse' })">驳回修改</el-button>
          <el-button v-if="showRevoke" size="small" class="revoke-btn common-btn" @click="toAudit({ isRevoke: true })">撤回待审核</el-button>
          <el-button v-if="showSyncBtn" :disabled="syncLoading" size="small" type="primary" class="common-btn" @click="syncData()">{{ syncLoading?'数据同步中':'立即同步' }}<i v-if="syncLoading" class="el-icon-loading"/></el-button>
          <btnGroup
            v-if="tabs.length"
            ref="btnGroupRef"
            :list="[
              {label:'导出', exportApi:'/admin/queryPriceItem/list/export', exportName:'询价列表', beforeExport: exportBeforeExport, type: 'export'}
            ]"
            class="btns"
            style="margin-left:16px"
            @onComplate="exportComplete"
          />
        </template>
      </div>
      <div class="table-list">
        <div v-loading="listLoading" style="min-height: 100px;">
          <u-table
            v-show="list.items.length && tabs.length"
            ref="tableRef"
            :data="list.items"
            :row-height="49"
            :row-class-name="tableRowClassName"
            :border="true"
            beautify-table
            header-drag-style
            use-virtual
            class="fb-table"
            element-loading-text="加载中..."
            empty-text="暂无数据"
            header-cell-class-name="order-data-header-cell"
            fit
            hightlight-current-row
            @select="selectTable"
            @select-all="selectTable">
            <u-table-column
              :fixed="useFixed"
              align="center"
              type="selection"
              width="50"
            />
            <u-table-column :fixed="useFixed" align="left" label="询价状态" min-width="110">
              <template slot-scope="scope">
                <div class="status">
                  <div :class="`color-${scope.row.status}`" class="dot"/>
                  <div>{{ scope.row.status | queryPriceStatusFilter }}<span v-if="scope.row.status === 0 || scope.row.status === 3">(<span :style="{color:scope.row.isRead?'#999999':'#406EFF'}">{{ `${scope.row.isRead?'已读':'未读'}` }}</span>)</span></div>
                </div>
              </template>
            </u-table-column>
            <u-table-column :fixed="useFixed" align="left" label="账号信息" min-width="130">
              <template slot-scope="scope">
                <accountIColumn :row="scope.row" @updateInfo="$emit('updateInfo')"/>
              </template>
            </u-table-column>
            <u-table-column align="left" label="本次报价(元)" min-width="200">
              <template slot="header" slot-scope="scope">
                <div class="table-header">
                  <div class="flex">
                    <span class="label">{{ scope.column.label }}</span>
                    <tipIcon :content="tip" class="ml2" use-html max-width="350px"/>
                  </div>
                </div>
              </template>
              <template slot-scope="scope">
                <template v-if="scope.row.nowPrice && scope.row.nowPrice.length">
                  <div v-for="(item, index) in scope.row.nowPrice" :key="index" class="price">
                    <ToolTip :content="`${item.name}:${item.value || item.value === 0? item.value : '--'}`" placement="left">
                      <div class="ellipsisOne flex-center" style="overflow: hidden">
                        <span class="price-name ellipsisOne" style="white-space: nowrap; display: inline-block">{{ item.name }}</span>：
                        <div :style="getPriceStyle(item)" class="ellipsisOne">{{ item.value || item.value === 0? item.value : '--' }}</div>
                      </div>
                    </ToolTip>
                  </div>
                </template>
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="上次报价(元)" min-width="200">
              <template slot-scope="scope">
                <template v-if="scope.row.lastPrice && scope.row.lastPrice.length">
                  <div v-for="(item, index) in scope.row.lastPrice" :key="index" class="price">
                    <ToolTip :content="`${item.name}:${item.value || item.value === 0? item.value : '--'}`" placement="left">
                      <div class="ellipsisOne flex-center" style="overflow: hidden">
                        <span class="price-name ellipsisOne" style="white-space: nowrap; display: inline-block">{{ item.name }}</span>：
                        <div class="ellipsisOne">{{ item.value || item.value === 0? item.value : '--' }}</div>
                      </div>
                    </ToolTip>
                  </div>
                </template>
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="报价是否更新" min-width="110">
              <template slot-scope="scope">
                <span>{{ scope.row.isPriceUpdate ? '是':'否' }}</span>
              </template>
            </u-table-column>
            <u-table-column align="left" label="蒲公英后台报价截图" min-width="200">
              <template slot-scope="scope">
                <FileShowList
                  v-if="Array.isArray(scope.row.attachmentFile) && scope.row.attachmentFile.length"
                  :file-list="scope.row.attachmentFile"
                  is-show-single-file
                />
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="更多上刊信息" min-width="200">
              <template slot-scope="scope">
                <template v-if="scope.row.moreInfo && scope.row.moreInfo.length">
                  <div v-for="(item, index) in scope.row.moreInfo" :key="index" class="price">
                    <ToolTip :content="`${item.name}:${item.value || item.value === 0? item.value : '--'}`" placement="left">
                      <div class="ellipsisOne flex-center" style="overflow: hidden">
                        <span class="price-name ellipsisOne" style="white-space: nowrap; display: inline-block">{{ item.name }}</span>：
                        <div class="ellipsisOne">{{ item.value || item.value === 0? item.value : '--' }}</div>
                      </div>
                    </ToolTip>
                  </div>
                </template>
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="地址变更信息" min-width="160">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.address" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="反馈记录" min-width="110">
              <template slot-scope="scope">
                <div v-if="scope.row.queryOrderFeedbacks && scope.row.queryOrderFeedbacks.length">
                  <div class="price"><span class="price-name">{{ scope.row.queryOrderFeedbacks[0].operator }}：</span>{{ scope.row.queryOrderFeedbacks[0].content?scope.row.queryOrderFeedbacks[0].content:scope.row.queryOrderFeedbacks[0].operateContent }}</div>
                  <el-popover
                    v-if="scope.row.queryOrderFeedbacks.length > 1"
                    placement="top"
                    width="382"
                    popper-class="fly-feedback-popover"
                    trigger="click">
                    <Title title="反馈记录"/>
                    <div class="popover-content">
                      <div v-for="(item, index) in scope.row.queryOrderFeedbacks" :key="index" class="item">
                        <div class="title"><ToolTip :content="item.operator + '：' + item.operateContent" class="operateContent"/><div class="time">{{ format(item.time,'YYYY/MM/DD HH:mm') }}</div></div>
                        <div v-if="item.content" :style="{background: item.operateContent === '驳回修改'? '#F2F5FA' : '#FAFAFC'}" class="content">回复：{{ item.content }}</div>
                      </div>
                    </div>
                    <span slot="reference" class="check-more">查看更多</span>
                  </el-popover>
                </div>
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="现维护经纪人" min-width="110">
              <template slot-scope="scope">
                <CheckUserInfo
                  v-if="scope.row.followContractBroker"
                  :user-list="scope.row.followContractBroker"
                  multiple
                />
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="签单签约经纪" min-width="110">
              <template slot-scope="scope">
                <CheckUserInfo v-if="scope.row.contractBroker" :label="scope.row.contractBroker" :user-id="scope.row.contractBrokerId" />
                <div v-else>--</div>
              </template>
            </u-table-column>
            <el-table-column align="left" label="签约所属部门" min-width="110">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.signDeptName" />
              </template>
            </el-table-column>
            <u-table-column align="left" label="供应商" min-width="110">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.channelName" />
              </template>
            </u-table-column>
          </u-table>
          <EmptyPlaceholder v-show="list.items.length === 0 || !tabs.length" slot="empty" :empty-text="tabs.length ? '暂无数据' : '暂无权限，请联系管理员'" mode="border" style="margin-bottom: 24px" />
          <el-row v-show="list.items.length" type="flex" align="center">
            <div style="flex:1;display:flex;align-items:center;">
              <SelectionNum :select-item="multipleSelectionAll" style="flex:1;" @clearMixinSelection="clearMixinSelection" />
            </div>
            <el-pagination
              :current-page.sync="page"
              :page-size="perPage"
              :total="list.total"
              :page-sizes="[20, 50, 100, 250, 500]"
              :layout="showMobilePage ? pageLayout : 'total, prev, pager, next, sizes, jumper'"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange" />
          </el-row>
        </div>
      </div>
    </div>
    <accountDialog ref="accountDialog" :fly-query-id="flyQueryId" :show-submit-tip="false" dialog-title="选择要询价的账号" show-price-status show-notice-status btn-text="确认追加" @submit="addAccount"/>
    <additionalDialog ref="additionalDialog" @updateInfo="$emit('updateInfo')" @submit="additional"/>
    <editDialog ref="editDialog" :allow-disable="false" title="请确认是否驳回" placeholder="请输入驳回备注" @submit="submitAudit(getApproveStatus({ type:'refuse' }),$event)"/>
  </div>
</template>
<script>
import axios from 'axios';// 取消未完成请求
import { mapState } from 'vuex';
import btnGroup from '@/components/Common/baseComponent/btnGroup';
import DetailTabs from '@/components/Common/baseComponent/DetailTabs';
import EmptyPlaceholder from '@/components/Common/emptyPlaceholder';
import accountDialog from '@/views/flyNotice/components/accountDialog';
import additionalDialog from './editDialog';
import platformIcon from '@/components/Common/platformIcon';
import ListTab from '@/components/ListTab';
import FileShowList from '@/components/CreateOrder/fileShowList';
import editDialog from './editDialog';
import Title from '@/components/Title';
import accountIColumn from './accountIColumn.vue';
import { adviseTabList, adviseList, additionalAccount, additional, editAccountStatus,
  querySyncStatus, syncAccountPrice, press, notice } from '@/api/flyPrice';
import { platformList } from '@/api/select';
import { getDepartmentAll } from '@/api/config';
import { numberTextFormat } from '@/filters/number';
import { queryPriceStatus, queryPriceStatusFilter } from '@/filters/status';
import { format } from '@/filters/date';
import TableAdaptive from '@/mixins/tableAdaptive';
import tableSelections from '@/mixins/tableSelections';
import mobileTable from '@/mixins/mobileTable';
import { hasRouteAuth } from '@/utils/permission';
import { showModal } from '@/utils/message';
import { paramsAryToStr } from '@/utils/paramsFormat';

export default {
  components: {
    DetailTabs,
    EmptyPlaceholder,
    btnGroup,
    accountDialog,
    additionalDialog,
    platformIcon,
    ListTab,
    FileShowList,
    editDialog,
    Title,
    accountIColumn
  },
  filters: {
    queryPriceStatusFilter,
    numberTextFormat
  },
  mixins: [TableAdaptive, tableSelections, mobileTable],
  props: {
    flyQueryId: {
      type: Number,
      default: -1
    },
    showPriceBtn: {
      type: Boolean,
      default: true
    },
    isApprovalStatus: {
      type: Boolean,
      default: false
    },
    isCreator: {
      type: Boolean,
      default: true
    },
    status: {// 询价单状态
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      tabs: [],
      list: {
        items: [],
        total: 0
      },
      deptTreeList: [],
      isUmyTable: true,
      idKey: 'id', // 多选框参数
      tableRefName: 'tableRef',
      tabStatus: -2,
      page: 1,
      perPage: 10,
      paramsObj: {},
      listLoading: false,
      orderPlatformOption: [],
      orderFormOption: [],
      cancelToken: null,
      timer: null,
      syncLoading: false,
      tip: `<div>点击［立即同步］按钮后报价信息会同步至账号资源</div><br><div>1、若本次报价高于账号资源当前最新报价，价格显示为红色</div><br><div>2、若本次报价低于账号资源当前最新报价，价格显示为绿色</div><br><div>3、价格未发生变化或未进行填写时，价格颜色不变</div>`
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    showSyncBtn() {
      return this.status !== 3 && this.isCreator && this.tabStatus === 2;
    },
    // tabStatus 0待回复 1待审核 2已完成 3待调整 4待签约确认 6待商务确认
    showAddRemarkBtn() {
      return this.showPriceBtn && this.tabStatus === 0;
    },
    showAddAccount() {
      return this.showPriceBtn && this.tabStatus !== 2 && this.tabs.length;
    },
    showAuditBtn() {
      return this.isApprovalStatus && [1, 4, 6].includes(this.tabStatus);
    },
    showRevoke() {
      return this.isApprovalStatus && this.tabStatus === 2;
    },
    showPressBtn() {
      return this.showPriceBtn && this.tabStatus === 0;
    },
    showNoticeBtn() {
      return this.showPriceBtn && this.tabStatus === 4;
    },
    arrayKeyArr() {
      return ['signDeptIds'];
    },
    filterList() {
      const arr = [
        // 输入框
        { keyword: 'channelName', name: '供应商', labelWidth: '80px', type: 'input' },
        { keyword: 'accountName', name: '账号', labelWidth: '100px', type: 'input' },
        { keyword: 'nowPrice', name: '本次报价', labelWidth: '80px', type: 'input' },
        { keyword: 'lastPrice', name: '上次报价', labelWidth: '100px', type: 'input' },
        { keyword: 'responsed', name: '反馈记录', labelWidth: '80px', type: 'input' },
        { keyword: 'followContractBroker', name: '现维护经纪人', labelWidth: '100px', type: 'input', doubleClick: true, placeholder: '请输入，双击填充当前用户' },
        { keyword: 'contractBroker', name: '签单签约经纪', labelWidth: '100px', type: 'input', doubleClick: true, placeholder: '请输入，双击填充当前用户' },
        // 下拉
        { keyword: 'platformName', name: '下单平台', type: 'select', options: this.orderPlatformOption, valueName: 'label', isSearch: true },
        { keyword: 'status', name: '状态', type: 'select', options: queryPriceStatus },
        { keyword: 'isRead', name: '阅读状态', type: 'select', options: [{ value: true, label: '已读' }, { value: false, label: '未读' }] },
        { keyword: 'isPriceUpdate', name: '报价是否更新', type: 'select', options: [{ value: 1, label: '是' }, { value: 0, label: '否' }] },
        { keyword: 'signDeptIds', name: '签约所属部门', type: 'cascaderSelectWithChild', childrenVal: 'children', options: this.deptTreeList }
      ];
      return arr;
    }
  },
  watch: {
    list: {
      handler: function(data) {
        this.$nextTick(() => {
          if (this.setSelectRow) {
            this.setSelectRow(data.items);
          }
        });
      },
      deep: true
    }
  },
  created() {
    this.fetchData(true);
    this.platformList();
    this.queryDeptTreeList();
  },
  methods: {
    hasRouteAuth,
    format,
    handlePress() {
      if (!this.multipleSelectionAll.length) {
        this.$message.warning('请选择要再次发送提醒的账号');
        return;
      }
      this.$confirm('是否再次提醒达人进行询价回复?', {
        confirmButtonText: '确定',
        type: 'warning',
        showClose: false,
        center: true,
        iconClass: 'charge-icon',
        customClass: 'del-message del-message-cancel'
      }).then(() => {
        const params = {
          id: this.flyQueryId,
          queryPriceAdvises: this.multipleSelectionAll
        };
        press(params).then(res => {
          if (res.code === 200) {
            this.$message.success('发送成功');
          }
        });
      }).catch(() => {
        return;
      });
    },
    handleNotice() {
      if (!this.multipleSelectionAll.length) {
        this.$message.warning('请选择要再次发送提醒的账号');
        return;
      }
      this.$confirm('是否通知签约经纪进行确认?', {
        confirmButtonText: '确定',
        type: 'warning',
        showClose: false,
        center: true,
        iconClass: 'charge-icon',
        customClass: 'del-message del-message-cancel'
      }).then(() => {
        const params = {
          id: this.flyQueryId,
          queryPriceAdvises: this.multipleSelectionAll
        };
        notice(params).then(res => {
          if (res.code === 200) {
            this.$message.success('发送成功');
          }
        });
      }).catch(() => {
        return;
      });
    },
    tableRowClassName({ row, rowIndex }) {
      const baseClass = '';
      if (this.multipleSelectionAll && this.multipleSelectionAll.length > 0) {
        const ids = this.multipleSelectionAll.map(i => i[this.idKey]);
        return ids.includes(row[this.idKey]) ? `table-selected ${baseClass}` : baseClass;
      }
      return baseClass;
    },
    updateInfo() {
      this.fetchData(true);
      this.$refs['accountDialog'].fetchData(true);
    },
    // 审核通过或者驳回 0驳回修改；1审批通过；2撤回待审核 3签约通过 4签约驳回 5商务通过 6商务驳回
    toAudit({ type, isRevoke }) {
      const approveStatus = this.getApproveStatus({ type, isRevoke });
      if (!(this.list.items && this.list.items.length)) {
        this.$message.warning('暂无数据可操作');
        return;
      }
      if ([0, 4, 6].includes(approveStatus)) {
        this.$refs['editDialog'].openDialog();
      } else {
        const tip = [1, 3, 5].includes(approveStatus) ? '请确认是否通过审核' : '请确认是否撤回待审核';
        showModal(tip, '', {
          iconClass: 'charge-icon'
        }).then(() => {
          this.submitAudit(approveStatus);
        }).catch(_ => {
          return false;
        });
      }
    },
    getApproveStatus({ type, isRevoke }) {
      if (isRevoke) return 2;
      return {
        1: { 'refuse': 0, 'pass': 1 },
        4: { 'refuse': 4, 'pass': 3 },
        6: { 'refuse': 6, 'pass': 5 }
      }[this.tabStatus][type];
    },
    submitAudit(approveStatus, remark = '') {
      let data = {
        queryPriceAdvises: this.getQueryPriceAdvises(),
        approveStatus
      };
      if (remark) {
        data.remark = remark;
      }
      data = Object.assign(data, this.formatParams());
      editAccountStatus(data).then(res => {
        let tip = '审批成功';
        if ([0, 4, 6].includes(approveStatus)) tip = '驳回修改成功';
        if (approveStatus === 2) tip = '撤回待审核成功';
        this.$message.success(tip);
        this.$emit('updateInfo');
        this.clearMixinSelection();
      }).catch(err => {
        console.log(err);
      });
    },
    // 同步询价
    syncData() {
      if (!(this.list.items && this.list.items.length)) {
        this.$message.warning('暂无数据可操作');
        return;
      }
      showModal('请确认是否立即同步价格数据至账号资源及飞博供应商', '', {
        iconClass: 'charge-icon'
      }).then(() => {
        let data = {
          queryPriceAdvises: this.getQueryPriceAdvises()
        };
        data = Object.assign(data, this.formatParams());
        this.syncLoading = true;
        if (!this.timer) {
          this.setTimer();
        }
        syncAccountPrice(data).then(res => {
          if (!this.timer) {
            this.setTimer();
          }
        }).catch(err => {
          this.syncLoading = false;
          console.log(err);
        });
      }).catch(_ => {
        return false;
      });
    },
    querySyncStatus() {
      querySyncStatus({ flyQueryId: this.flyQueryId }).then(res => {
        if (res.code === 200) {
          if (res.status) {
            this.syncLoading = false;
            this.clearTimer();
            this.$message.success('同步成功');
            this.$emit('updateInfo');
          } else {
            this.syncLoading = true;
          }
        }
      }).catch(err => {
        this.syncLoading = false;
        console.log(err);
      });
    },
    // 轮询同步状态
    setTimer(time = 1500) {
      this.timer = setInterval(() => {
        this.querySyncStatus();
      }, time);
    },
    // 刷新列表，清除定时器
    clearTimer() {
      clearInterval(this.timer);
      this.timer = null;
    },
    // 导出
    exportBeforeExport() {
      const params = this.formatParams(true);
      if (this.multipleSelectionAll.length > 0) {
        params.ids = this.multipleSelectionAll.map(el => el.id).join(',');
      }
      this.$refs['btnGroupRef'] && this.$refs['btnGroupRef'].btnExport(params);
    },
    exportComplete() {
      this.$emit('updateInfo');
    },
    // 获取下单平台的列表
    async platformList() {
      try {
        const result = await platformList();
        result.data.forEach((i) => {
          i.label = i.value;
          i.value = i.id;
        });
        this.orderPlatformOption = result.data;
      } catch (error) {
        console.log(error);
      }
    },
    // 获取部门列表
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    async getTabs() {
      const params = this.formatParams();
      const res = await adviseTabList(params);
      if (res.code !== 200) {
        this.$message.error(res.message);
        return;
      }
      this.tabs = res.data || [];
      if (this.tabStatus === -2) {
        this.tabStatus = this.tabs.length && this.tabs[0].id || -2;
        if (this.$route.query.queryTab) {
          const idx = this.tabs.findIndex(it => it.id === Number(this.$route.query.queryTab));
          if (idx === -1) {
            this.$message.warning('无权限，请联系管理员开通');
            return;
          }
          this.tabStatus = Number(this.$route.query.queryTab);
        }
      }
    },
    async existAuditAccount() {
      const params = this.formatParams();
      const res = await adviseTabList(params);
      if (res.code !== 200) {
        this.$message.error(res.message);
        return false;
      }
      const fitTabStatus = [1, 4, 6];
      const tabs = (res.data || []).filter(tabItem => fitTabStatus.includes(tabItem.id));
      if (tabs.find(i => i.num > 0)) {
        return true;
      }
      return false;
    },
    async fetchData(reset = false) {
      if (this.cancelToken) this.cancelToken.cancel('cancel');
      const source = axios.CancelToken.source();// 用于取消请求
      this.cancelToken = source;
      await this.getTabs();
      if (this.tabStatus === -2) return;
      this.listLoading = true;
      if (reset) this.page = 1;
      const params = this.formatParams(true);
      adviseList(params, source.token).then(res => {
        this.listLoading = false;
        if (res.code !== 200) {
          this.$message.error(res.message);
          return;
        }
        this.list = res.data;
      }).catch(err => {
        this.listLoading = false;
        console.log(err);
      });
    },
    formatParams(isListParams = false) {
      const params = isListParams ? {
        page: this.page,
        perPage: this.perPage,
        tabStatus: this.tabStatus
      } : {};
      const paramsObj = Object.assign(params, this.paramsObj);
      Object.keys(paramsObj).forEach(key => {
        if (Array.isArray(paramsObj[key])) {
          paramsObj[key] = paramsObj[key].join(',');
        }
      });
      paramsAryToStr(this.arrayKeyArr, paramsObj);
      paramsObj.flyQueryId = this.flyQueryId;
      return paramsObj;
    },
    getQueryPriceAdvises(list = this.multipleSelectionAll, isNeedFilter = true) {
      const advises = [];
      if (list.length) {
        list.forEach(j => {
          advises.push({
            wxUserId: j.wxUserId,
            accountId: j.accountId,
            accountName: j.accountName
          });
        });
      }
      return advises;
    },
    // 追加说明
    openAdditionalDialog() {
      if (!this.multipleSelectionAll.length) {
        this.$message.warning('请选择需要追加说明的账号');
        return;
      }
      this.$nextTick(() => {
        this.$refs['additionalDialog'].openDialog();
      });
    },
    // 追加说明
    additional(description = '') {
      const data = {
        queryPriceAdvises: this.getQueryPriceAdvises(),
        flyQueryId: this.flyQueryId,
        description
      };
      additional(data).then(res => {
        this.loading = false;
        if (res.code !== 200) {
          this.$message.error(res.message);
          return;
        }
        this.$message.success('追加成功');
        this.$emit('updateInfo');
      }).catch(err => {
        console.log(err);
      });
    },
    // 追加账号
    additionalAccount() {
      this.$refs['accountDialog'].openDrawer();
    },
    addAccount(list = []) {
      const data = {
        flyQueryId: this.flyQueryId,
        queryPriceAdvises: []
      };
      if (list && list.length) {
        data.queryPriceAdvises = this.getQueryPriceAdvises(list, false);
        additionalAccount(data).then(res => {
          if (res.code !== 200) {
            this.$message.error(res.message);
            return;
          }
          this.$refs['accountDialog'].handleClose();
          this.$emit('updateInfo');
        }).catch(err => {
          this.$refs['accountDialog'].handleClose();
          console.log(err);
        });
      }
    },
    handleTabClick(id) {
      this.tabStatus = id;
      this.list = { items: [] };
      this.multipleSelectionAll = [];
      this.fetchData(true);
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.fetchData(true);
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.fetchData();
    },
    getPriceStyle(item) {
      return {
        1: { color: '#FF4E5F' },
        2: { color: '#31CC9C' }
      }[item.priceChangeStatus] || {};
    }
  }
};
</script>
<style lang="scss" scoped>
$bgc: #FD8546 0, #FD8546 1, #31CC9C 2, #999 3;
  .mobile-notice {
    .filter {
      flex-wrap: wrap;
    }
    .tab-wrap {
      border-bottom: 1px solid #ddd;
    }
    .filter-wrap {
      padding-left: 8px;
    }
    .filter-btn {
      box-shadow: -5px 2px 8px -3px #dde1ea;
      ::v-deep .mobile-icon {
        margin: 0 !important;
        padding: 6px 0 4px 8px;
        box-shadow: unset;
        .text {
          display: none;
        }
      }
    }
    .notice-btn-group {
      display: flex;
      margin-bottom: 8px;
    }
  }
  .table-header {
    display: inline-block;
    .flex {
      display: flex;
      align-items: center;
    }
  }
  .tabs {
    padding-left: 0 !important;
    flex: 1;
    height: unset !important;
    ::v-deep .list-tab {
      padding-left: 0 !important;
    }
  }
  .price {
    font-size: 12px;
    .price-name {
      font-size: 12px;
      color: #999999;
      overflow: visible;
    }
  }
  .fly-feedback-popover {
    .popover-content {
      max-height: 200px;
      overflow-y: auto;
      padding-right: 6px;
      margin-top: 8px;
      .item {
        margin-bottom: 12px;
        .title {
          display: flex;
          align-items: center;
          width: 100%;
          font-size: 12px;
          color: #999999;
          margin-bottom: 4px;
          .operateContent {
            max-width: 230px;
          }
          .time {
            flex: 1;
            text-align: right;
            white-space: nowrap;
          }
        }
        .content {
          display: flex;
          align-items: center;
          min-height: 40px;
          padding:10px 8px;
          border-radius: 4px;
          font-size: 14px;
          color: #333333;
        }
      }
    }
  }
  .check-more {
    color: #406EFF;
    cursor: pointer;
  }
  .revoke-btn {
    border: 1px #FF4E5F solid;
    color: #FF4E5F;
  }
	.flyPrice{
    .flyPrice-list{
      margin-top: 12px;
    }
    .operate{
      display: flex;
      align-items: center;
    }
    .border-left {
      position: relative;
      padding-left: 6px;
      margin-left: 6px;
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        margin-top: -7px;
        width: 1px;
        background: #ddd;
        height: 14px;
      }
    }
		.filter {
			display: flex;
			align-items: center;
      margin-bottom: 16px;
      ::v-deep .el-button {
        padding-left: 12px;
        padding-right: 12px;
      }
		}
    .status{
      display: flex;
      align-items: center;
      .text{
        white-space: nowrap;
      }
    }
    .dot {
      width: 4px;
      height: 4px;
      border-radius: 50%;
      margin-right: 5px;
      @each $c, $i in $bgc {
        &.color-#{$i} {
          background: $c;
        }
      }
    }
    .btns{
      ::v-deep {
        .fb-button-item{
          white-space: nowrap !important;
        }
      }
    }
    .common-btn {
      height: 32px;
    }
    .ellipsis{/* 单行溢出隐藏 */
      width: 110px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    .pointer{
      cursor: pointer;
    }
    .tag-wrap{
      display: flex;
      align-items: center;
    }
    .tag{
      display: inline-block;
      max-width: 60px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      color:#406EFF;
      font-size: 12px;
      padding: 0px 8px;
      background: #eff4ff;
      border-radius: 10px;
      margin-right: 4px;
    }
	}
</style>
<style>
  .fly-feedback-popover {
    border-radius: 8px;
    padding: 20px 14px 20px 20px !important;
  }
</style>
